import Row from "./Row";
import ColGroup from "./ColGroup";
import { useForm } from "../../../framework/common/context/metadata-context";
import clsx from "clsx";
import FixedTable from "./FixedTable";
import { forwardRef, useLayoutEffect, useState, useRef, useEffect } from "react";
import eventBus from "../../../framework/common/eventBus";
import request from "../../../framework/common/utils/request";
import { openWin } from "../../../framework/common/utils";
import Summary from "./Summary";
import { useEventListener, useThrottleFn } from "ahooks";
import HeaderTable from "./HeaderTable";
import OperationTable from "./OperationTable";
import { fieldFilter, fieldFilterNormal } from "../../../framework/common/utils/filter";
import jQuery from "jquery";
import { InjectProvider } from "../../../framework/common/context/inject-context";
import { mergecalculateFormData } from "../../../apis/mergeFormData";
import Header from "./Header";
import PrintSummary from "./PrintSummary";
window.jQuery = jQuery;
function  SubTable({ data, group, isVirtualTable ,aref}) {
  const form = useForm();
  const { data: tplData, urlPrefix, params } = useForm().root;
  const headerTableRef = useRef();
  const summaryRef = useRef();
  const wrapperRef = useRef();
  const [scrollBarWidth, setScrollBarWidth] = useState(0);
  const [hasScrollBarX, setHasScrollBarX] = useState(false);
  const isPrint = form.mode === "Print";

  const groupInfoRef = useRef({ stage: "init" });

  if (tplData?.hideInfo?.delete_col_arr?.length > 0) {
    //shit一样的数据结构
    group.fields.forEach((field) => {
      let code = `${group.code}.${field.code}`;
      if (tplData.hideInfo.delete_col_arr.includes(code)) {
        if (field.isHidden !== true) {
          field.isHidden = true;
          tplData.hideTrackingInfo.add(field);
        }
      }
    });
  }

  useEffect(() => {
    if (wrapperRef.current) {
      var scrollBarWidth = wrapperRef.current.offsetHeight - wrapperRef.current.clientHeight;
      if (scrollBarWidth > (form.scrollBarWidth || 0)) form.scrollBarWidth = scrollBarWidth;

      //计算scroll bar Y 宽度
      let barWidth = wrapperRef.current.offsetWidth - wrapperRef.current.clientWidth;
      if (barWidth < 5 && scrollBarWidth !== 0) {
        setScrollBarWidth(0);
      } else if (barWidth > 5 && barWidth != scrollBarWidth) {
        setScrollBarWidth(barWidth);
      }
    }

    //表格布局准备就绪
    setTimeout(() => {
      eventBus.publish(group.code + ".ready");
    }, 0);
  });

  const leftFixedTableRef = useRef();
  const rightFixedTableRef = useRef();
  const lastScrollLeftRef = useRef(0);
  const lastScrollTopRef = useRef(0);
  const tickingRef = useRef(false);

  function syncScroll() {
    if (summaryRef.current) {
      summaryRef.current.style.transform = "translateX(" + -1 * lastScrollLeftRef.current + "px)";
      // summaryRef.current.style["-ms-transform"] = "translateX(" + -1 * lastScrollLeftRef.current + "px)";
    }

    if (headerTableRef.current) {
      headerTableRef.current.style.transform = "translateX(" + -1 * lastScrollLeftRef.current + "px)";
      // headerTableRef.current.style["-ms-transform"] = "translateX(" + -1 * lastScrollLeftRef.current + "px)";
    }

    if (leftFixedTableRef.current) {
      leftFixedTableRef.current.style.transform = "translateY(" + -1 * lastScrollTopRef.current + "px)";
      //ie9
      // leftFixedTableRef.current.style["-ms-transform"] = "translateY(" + -1 * lastScrollTopRef.current + "px)";
    }

    if (rightFixedTableRef.current) {
      rightFixedTableRef.current.style.transform = "translateY(" + -1 * lastScrollTopRef.current + "px)";
      //ie9
      // leftFixedTableRef.current.style["-ms-transform"] = "translateY(" + -1 * lastScrollTopRef.current + "px)";
    }
  }

  useEffect(() => {}, []);
  useEventListener(
    "scroll",
    function (e) {
      lastScrollLeftRef.current = e.target.scrollLeft;
      lastScrollTopRef.current = e.target.scrollTop;
      if (!tickingRef.current) {
        window.requestAnimationFrame(function () {
          syncScroll();
          tickingRef.current = false;
        });

        tickingRef.current = true;
      }
    },
    {
      target: wrapperRef,
    }
  );

  useEffect(() => {
    //子表目前渲染阶段 end表示结束渲染
    groupInfoRef.current.stage = "end";
  });
  const { run } = useThrottleFn(
    () => {
      eventBus.publish(`group.update.${group.code}`);
    },
    { wait: 500 }
  );
  useLayoutEffect(() => {
    window.addEventListener("resize", run, false);
    return () => {
      window.removeEventListener("resize", run, false);
    };
  }, []);
  var [virtualTableState, setvirtualTableState] = useState(isVirtualTable === true ? 2 : 1);

  //导出excel
  function exportExcel() {
    let groupCode = group.code;
    let $groupHead = form.subTableTheadRef[groupCode]; //拿到当前子表的colgroup dom
    let tableData = [],
      headerData = [];
    //1.遍历thead拿到表头数据
    $groupHead.current.childNodes.forEach(function (c, index) {
      //遍历界面上的thead内td
      let obj = {
        width: c.getBoundingClientRect().width,
        value: c.innerText,
        //千分位 百分比 小数位配置，默认给空字符串，下面再循环查找列配置从列配置取一遍，如果不给这3个属性，后端会报错
        is_thousandth: "",
        percentage: "",
        precision: "",
      };
      group.fields.find(function (item) {
        //遍历当前子表的列字段
        if (item?.designProps?.title == c.innerText) {
          //如果界面上的文本 == 列字段的显示标题
          //取列字段的千分位 百分比 小数位配置，没有默认给空字符串
          obj.is_thousandth = item.props?.is_thousandth === undefined ? "" : String(item.props.is_thousandth);
          obj.percentage = item.props?.percentage === undefined ? "" : String(item.props.percentage);
          obj.precision = item.props?.precision === undefined ? "" : Number(item.props.precision);
          return true;
        }
      });
      headerData.push(obj);
    });
    //2.遍历tbody，获得tbody数据
    let $tbody = aref.current.getElementsByTagName("tbody")[0];

    let rowSpanHolder = {};
    $tbody.childNodes.forEach(function (row, rowIndex) {
      let rowData = [];
      let increase = 0;
      row.childNodes.forEach(function (tdItem, colIndex) {
        if (rowSpanHolder[colIndex] > 0) {
          rowSpanHolder[colIndex]--;
          rowData[colIndex] = {
            value: "",
            ishide: false,
          };
          increase++;
        } else {
          if (tdItem.rowSpan > 1) {
            rowSpanHolder[colIndex] = tdItem.rowSpan;
          }
        }
        let value = tdItem.innerText;
        let tdData = {
          value: value,
          ishide: false,
        };
        rowData[colIndex + increase] = tdData;
      });
      tableData.push(rowData);
    });

    //3.遍历tfoot，获得tfoot数据
    let $tfoot = document.querySelector(`#${group.code} .summary tr`);
    let rowData = [];
    $tfoot &&
      $tfoot.childNodes.forEach(function (row) {
        let tdData = {
          value: row.innerText,
          isFormatless: true,
          ishide: false,
        };
        rowData.push(tdData);
      });
    if (rowData.length > 0 && tableData.length > 0 && rowData.length === tableData[0]?.length) {
      tableData.push(rowData);
    }

    //4.发送请求导出excel
    request({
      url: "/flowinstance/process/export-table",
      method: "POST",
      data: {
        headerData: headerData,
        tableData: tableData,
        tableCode: group.code,
        tableName: group.name,
      },
    })
      .then(function (result) {
        if (result.code === 1) {
          let openUrl = "/flowinstance/process/export-table?id=" + result.data.id;
          if (urlPrefix) {
            // openUrl = urlPrefix + openUrl;//需要确定是否需要带租户
          }
          openWin(openUrl); //打开导出Excel地址
        } else {
        }
      })
      .catch(function (result) {});
  }
  useLayoutEffect(() => {
    //如果是虚拟dom，则执行导出PDF，虚拟dom由 导出excel 触发生成
    if (virtualTableState === 2) {
      exportExcel(); //导出excel
      setvirtualTableState(3);
    }
  }, []);
  const [hidden, setHidden] = useState(true);
  useEffect(() => {
    let $current = jQuery(wrapperRef.current);
    if ($current.length && $current[0].scrollHeight > 500) {
      hidden === true && setHidden(false);
    } else {
      hidden === false && setHidden(true);
    }

    if (wrapperRef?.current) setHasScrollBarX($current.hasScrollBar().horizontal);
  });

  let filteredFields = group.fields.filter(fieldFilter).filter((f) => f.isHidden !== true);
  if (filteredFields?.length === 0) {
    return null;
  }
  if (virtualTableState == 3) {
    //如果导出Excel完成，则返回null，table content不要渲染到页面
    return null;
  }


  if (group.cachedHeight === undefined) {
    group.cachedHeight = {};
  }
  if (group.cachedWidth === undefined) {
    group.cachedWidth = {};
  }
  let fields = group.fields;
  // console.log(group.code,form.mode)
  //计算分组内容相同时合并line_splicing
  let lineSplicingFields = group.fields.filter((f) => {
    //列开启了内容相同合并，且列的步骤权限为不可编辑时，才需要做合并
    return f?.designProps?.line_splicing === true && f.is_editable !== true;
  });
  lineSplicingFields.forEach((field) => {
    let code = field.designProps.code;
    let cusor = null;
    field.lineSpliceInfo = {};
    field.mergedCell = {};
    data.forEach((dataRow, dataRowIndex) => {
      let currentValue = dataRow[code];

      let isString = typeof currentValue === "string" || currentValue instanceof String;
      if ((!isString && currentValue) || (isString && currentValue.trim())) {
        if (cusor === null) {
          cusor = {
            index: dataRowIndex,
            value: currentValue,
            count: 1,
          };
        } else {
          if (currentValue === cusor.value) {
            field.mergedCell[dataRowIndex] = true;
            cusor.count++;
          } else {
            field.lineSpliceInfo[cusor.index] = cusor.count;
            cusor = {
              index: dataRowIndex,
              value: currentValue,
              count: 1,
            };
          }
        }
      }
    });

    if (cusor && cusor.count > 1 && field.lineSpliceInfo[cusor.index] === undefined) {
      field.lineSpliceInfo[cusor.index] = cusor.count;
    }
  });

  //如果当前列无数据，直接不显示当前列
  group.fields.forEach((field) => {
    if (field.isHiddenRows) {
      let hiddenRowsLength = field.isHiddenRows.filter((i) => i === true).length;
      if (hiddenRowsLength > 0 && hiddenRowsLength === data.length) {
        field.isAllRowhidden = true;
      } else {
        field.isAllRowhidden = false;
      }
    }
  });

  //编辑模式启用了删除显示删除操作列
  let hasOperationColumn = form.isDesign && group.isDelete;

  //打印模式禁用操作列
  if (isPrint) hasOperationColumn = false;

  if (hasOperationColumn) {
    //如果字段全部不能编辑，就不现实添加
    let anyEditable = group.columns.find((c) => c?.is_editable === true); //存在可编辑的列
    if (!anyEditable) {
      //不存在可编辑的列
      hasOperationColumn = false; //不显示删除操作列
    }
  }

  let tableWidth = group?.style?.width;
  let allFieldWidth = group.fields.filter(fieldFilter).reduce((previousValue, currentValue) => {
    return previousValue + (currentValue.isHidden == true ? 0 : currentValue?.style?.width || 85);
  }, 0);

  // if(allFieldWidth>tableWidth){
  tableWidth = group.style.width = allFieldWidth;
  // }

  let scale = 1;

  let tableViewPortWidth = 1039;

  if (hasOperationColumn) {
    tableViewPortWidth -= 64;
  }
  if (tableWidth < tableViewPortWidth) {
    scale = tableViewPortWidth / tableWidth;
  }

  // let tableWidth = group?.style?.width < 1040 ? 1040: group?.style?.width;
  // if(hasOperationColumn){//存在操作列
  //   tableWidth = tableWidth - (64 - scrollBarWidth);//子表宽度 - 操作列宽64 - 滚动条宽
  // }
  let isSetFixedColumnPc = false;
  // //没有出现滚动条&& 设置了冻结列并且冻结列大于1 && 查看模式
  // if (group?.style?.width > 1040 && group.isSetFixedColumnPc === true && group.fixedColumnPc >= 1 && form.isDisplay === true) {
  //   isSetFixedColumnPc = true;
  // }
  //没有出现滚动条&& 设置了冻结列并且冻结列大于1
  if (scale === 1 && group.isSetFixedColumnPc === true && group.fixedColumnPc >= 1 && hasScrollBarX) {
    isSetFixedColumnPc = true;
  }

  //打印模式禁用固定列
  if (isPrint) {
    isSetFixedColumnPc = false;
  }

  let marginRight = 0;
  let paddingRight = hasOperationColumn ? 64 - scrollBarWidth + "px" : 0;
  if (group.style.width > 970) {
    marginRight = hasOperationColumn ? 64 - scrollBarWidth + "px" : 0;
    paddingRight = 0;
  }
  let filterFields = group.fields?.filter(fieldFilter);
  //子表目前渲染阶段 init表示准备渲染 ,计算字段专用
  // groupInfoRef.current.
  // if(filterFields.find(f=>f.type==="calculation")){
    // groupInfoRef.current.calculateFormData= mergecalculateFormData(tplData)
    tplData.calculateFormData = mergecalculateFormData(tplData);//更新前端计算依赖的数据源
  // }


  let normalFilterFields = fields.filter(fieldFilterNormal);
  //渲染子表表格
  let theTable = (
    <InjectProvider value={{groupInfo: groupInfoRef.current}}>
      <div
        id={group.code + "Container"}
        ref={wrapperRef}
        style={{ paddingRight, overflowX: tableWidth < tableViewPortWidth ? "hidden" : "auto" }}
        className={clsx("h-auto runtime-data-list mainTable", form.showBorder && "hasBorder", hidden && "hiddenY", data?.length <= 0 && "noData")}
      >
        <table className={clsx("min-w-full inline-table table-process-form align-middle")} style={{ marginRight, width: tableWidth + "px" }}>
          {data.length > 0 && <ColGroup wrapperRef={wrapperRef} scale={scale} isFiexedTable={isSetFixedColumnPc} group={group} fields={group.fields}></ColGroup>}
          {isPrint && <Header wrapperRef={wrapperRef} isVirtualTable={isVirtualTable} group={group} fields={group.fields}></Header>}
          <tbody>
            {data.length > 0
              ? data.map((row, index) => {
                  return (
                    <Row
                      isVirtualTable={isVirtualTable}
                      normalFilterFields={normalFilterFields}
                      filterFields={filterFields}
                      isFiexedTable={isSetFixedColumnPc}
                      groupCode={group.code}
                      group={group}
                      rowIndex={index}
                      key={row.__cid__}
                      row={row}
                      fields={fields}
                    ></Row>
                  );
                })
              : !isPrint && (
                  <tr>
                    <td className="text-center text-color-999">暂无数据</td>
                  </tr>
                )}
          </tbody>
          {isPrint && <PrintSummary  scale={scale} paddingRight={paddingRight} data={data} group={group}></PrintSummary>}
        </table>
      </div>
    </InjectProvider>
  );

  let hasData = true;

  if (data?.length == 0) {
    hasData = false;
  }

  let operationTable;
  if (hasOperationColumn) {
    //右边的固定列，目前需求只有操作列删除
    operationTable = <OperationTable form={form} rightFixedTableRef={rightFixedTableRef} group={group} scrollBarWidth={scrollBarWidth} data={data}></OperationTable>;
  }


  if (filterFields?.length === 0) {
    return null;
  }

  //如果没有固定列
  if (isSetFixedColumnPc === false) {
    return (
      <div ref={aref} className="relative runtime-data-list-wrapper ">
        {isPrint !== true && (
          <HeaderTable
            scale={scale}
            hasOperationColumn={hasOperationColumn}
            scrollBarWidth={scrollBarWidth}
            hasData={hasData}
            ref={headerTableRef}
            isVirtualTable={isVirtualTable}
            data={data}
            group={group}
            isSetFixedColumnPc={isSetFixedColumnPc}
            wrapperRef={wrapperRef}
          ></HeaderTable>
        )}
        {theTable}
        {operationTable}
        {!isPrint && (
          <Summary hasOperationColumn={hasOperationColumn} scale={scale} paddingRight={paddingRight} ref={summaryRef} data={data} group={group} isSetFixedColumnPc={isSetFixedColumnPc}></Summary>
        )}
      </div>
    );
  }

  return (
    <FixedTable scale={scale} leftFixedTableRef={leftFixedTableRef} ref={aref} data={data} group={group}>
      <HeaderTable
        wrapperRef={wrapperRef}
        scale={scale}
        hasOperationColumn={hasOperationColumn}
        scrollBarWidth={scrollBarWidth}
        hasData={hasData}
        ref={headerTableRef}
        isVirtualTable={isVirtualTable}
        data={data}
        group={group}
        isSetFixedColumnPc={isSetFixedColumnPc}
      ></HeaderTable>
      {theTable}
      {operationTable}
      <Summary scale={scale} hasOperationColumn={hasOperationColumn} paddingRight={paddingRight} ref={summaryRef} data={data} group={group} isSetFixedColumnPc={isSetFixedColumnPc}></Summary>
    </FixedTable>
  );
}
export default forwardRef(function ({ data, group, isVirtualTable }, ref) {
  const [isReady, setIsReady] = useState(false);
  useEffect(() => {
    setTimeout(() => {
      setIsReady(true);
    }, 0);
  }, []);

  if (isReady === false) {
    return null;
  }
  return <SubTable data={data} group={group} isVirtualTable={isVirtualTable} aref={ref}></SubTable>;
});
